<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Lion Hunt Game</title>
    <style>
        canvas {
            border: 1px solid black;
            display: block;
            margin: 0 auto;
        }
        body {
            background-color: #333;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            height: 100vh;
            margin: 0;
            font-family: Arial, sans-serif;
        }
        #gameContainer {
            position: relative;
        }
        #startScreen {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: rgba(0, 0, 0, 0.8);
            color: white;
            padding: 20px;
            border-radius: 10px;
            text-align: center;
            z-index: 1;
        }
        #startButton {
            background-color: #4CAF50;
            border: none;
            color: white;
            padding: 15px 32px;
            text-align: center;
            text-decoration: none;
            display: inline-block;
            font-size: 16px;
            margin: 4px 2px;
            cursor: pointer;
            border-radius: 5px;
        }
        #startButton:hover {
            background-color: #45a049;
        }
    </style>
</head>
<body>
    <div id="gameContainer">
        <div id="startScreen">
            <h1>狮子捕猎游戏</h1>
            <p>使用方向键(↑↓←→)控制狮子移动</p>
            <p>接触到动物即可捕获</p>
            <button id="startButton">开始游戏</button>
        </div>
        <canvas id="gameCanvas"></canvas>
    </div>
    <script>
        // 游戏常量
        const SCREEN_WIDTH = 800;
        const SCREEN_HEIGHT = 600;
        const PLAYER_SPEED = 3;
        const GOAT_SPEED = 1.5;
        const TILE_SIZE = 32;
        const MAP_COLS = Math.ceil(SCREEN_WIDTH / TILE_SIZE);
        const MAP_ROWS = Math.ceil(SCREEN_HEIGHT / TILE_SIZE);
        const INITIAL_GOATS = 3;
        const MAX_GOATS = 5;
        const INITIAL_PIGS = 2;
        const MAX_PIGS = 4;
        const GOAT_SPAWN_INTERVAL = 5000;
        const RANDOM_MOVE_CHANCE = 0.01;
        const RANDOM_MOVE_DURATION = 60;
        const CELEBRATION_DURATION = 180; // 3秒 = 60帧/秒 * 3秒

        // 获取Canvas上下文
        const canvas = document.getElementById('gameCanvas');
        const ctx = canvas.getContext('2d');
        canvas.width = SCREEN_WIDTH;
        canvas.height = SCREEN_HEIGHT;

        // 捕获动画类
        class CaptureAnimation {
            constructor(x, y, points = 1) {
                this.x = x;
                this.y = y;
                this.points = points;
                this.lifetime = 60;
                this.currentFrame = 0;
            }
            
            update() {
                this.currentFrame++;
                this.y -= 0.5;
                this.lifetime--;
            }
            
            render(ctx) {
                ctx.fillStyle = this.points > 1 ? '#FFA500' : '#FFFF00';
                ctx.font = 'bold 24px Arial';
                ctx.fillText(`+${this.points}`, this.x, this.y);
            }
            
            isFinished() {
                return this.lifetime <= 0;
            }
        }

        // 玩家类
        class Player {
            constructor() {
                this.width = 48;
                this.height = 64;
                this.x = SCREEN_WIDTH / 2;
                this.y = SCREEN_HEIGHT / 2;
                this.speed = PLAYER_SPEED;
                this.direction = 'right';
                this.img = new Image();
                
                // 动画相关属性
                this.frameWidth = 48;
                this.frameHeight = 64;
                this.totalFrames = 4;
                this.currentFrame = 0;
                this.frameCounter = 0;
                this.frameDelay = 12;
                this.isMoving = false;
            }

            update(keys) {
                // 如果正在庆祝，不处理移动
                if (gameState.isCelebrating) {
                    gameState.celebrateFrame++;
                    
                    // 更新庆祝动画
                    this.frameCounter++;
                    if (this.frameCounter >= this.frameDelay) {
                        this.currentFrame = (this.currentFrame + 1) % this.totalFrames;
                        this.frameCounter = 0;
                    }
                    
                    // 确保完整播放3秒动画
                    if (gameState.celebrateFrame >= CELEBRATION_DURATION) {
                        gameState.isCelebrating = false;
                        gameState.celebrateFrame = 0;
                        console.log('庆祝动画结束');
                    }
                    return;
                }
                
                // 重置移动状态
                this.isMoving = false;
                
                // 移动逻辑
                if (keys.ArrowLeft) {
                    this.x -= this.speed;
                    this.direction = 'left';
                    this.isMoving = true;
                }
                if (keys.ArrowRight) {
                    this.x += this.speed;
                    this.direction = 'right';
                    this.isMoving = true;
                }
                if (keys.ArrowUp) {
                    this.y -= this.speed;
                    this.isMoving = true;
                }
                if (keys.ArrowDown) {
                    this.y += this.speed;
                    this.isMoving = true;
                }

                // 边界检查
                this.x = Math.max(0, Math.min(SCREEN_WIDTH - this.width, this.x));
                this.y = Math.max(0, Math.min(SCREEN_HEIGHT - this.height, this.y));
                
                // 更新动画
                if (this.isMoving) {
                    this.frameCounter++;
                    if (this.frameCounter >= this.frameDelay) {
                        this.currentFrame = (this.currentFrame + 1) % this.totalFrames;
                        this.frameCounter = 0;
                    }
                } else {
                    this.currentFrame = 0;
                }
            }
            
            // 庆祝捕获
            celebrate() {
                gameState.isCelebrating = true;
                gameState.celebrateFrame = 0;
                gameState.lastCaptureTime = Date.now();
                console.log('开始播放庆祝动画（3秒）');
            }
            
            // 获取庆祝动画的Y偏移（蹦跳效果）
            getCelebrateOffset() {
                if (!gameState.isCelebrating) return 0;
                
                const progress = gameState.celebrateFrame / CELEBRATION_DURATION;
                return Math.sin(progress * Math.PI * 4) * 10;
            }

            render(ctx) {
                ctx.save();
                
                // 计算当前帧在精灵图中的位置
                const sourceX = this.currentFrame * this.frameWidth;
                const sourceY = 0;
                
                // 计算庆祝动画的Y偏移
                const celebrateOffset = this.getCelebrateOffset();
                
                if (this.direction === 'right') {
                    ctx.scale(-1, 1);
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        -this.x - this.width, this.y - celebrateOffset,
                        this.width, this.height
                    );
                } else {
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        this.x, this.y - celebrateOffset,
                        this.width, this.height
                    );
                }
                ctx.restore();
            }

            getBounds() {
                return {
                    x: this.x,
                    y: this.y,
                    width: this.width,
                    height: this.height
                };
            }
        }

        // 羚羊类
        class Goat {
            constructor() {
                this.width = 48;
                this.height = 48;
                // 随机在地图边缘生成
                const spawnEdge = Math.floor(Math.random() * 4);
                switch(spawnEdge) {
                    case 0: // 上边
                        this.x = Math.random() * (SCREEN_WIDTH - this.width);
                        this.y = -this.height;
                        break;
                    case 1: // 右边
                        this.x = SCREEN_WIDTH;
                        this.y = Math.random() * (SCREEN_HEIGHT - this.height);
                        break;
                    case 2: // 下边
                        this.x = Math.random() * (SCREEN_WIDTH - this.width);
                        this.y = SCREEN_HEIGHT;
                        break;
                    case 3: // 左边
                        this.x = -this.width;
                        this.y = Math.random() * (SCREEN_HEIGHT - this.height);
                        break;
                }
                
                this.speed = GOAT_SPEED;
                this.direction = 'left';
                this.img = new Image();
                this.fleeDistance = 150;  // 减少检测距离
                
                // 随机移动相关属性
                this.moveTimer = 0;
                this.moveInterval = Math.random() * 1000 + 500;
                this.moveAngle = Math.random() * Math.PI * 2;
                this.isRandomMoving = false;
                this.randomMoveCounter = 0;
                this.randomMoveDirection = 0;
                
                // 动画相关属性
                this.frameWidth = 48;
                this.frameHeight = 48;
                this.totalFrames = 4;
                this.currentFrame = 0;
                this.frameCounter = 0;
                this.frameDelay = 12;
                this.isMoving = false;
            }

            update(player) {
                // 重置移动状态
                let wasMoving = this.isMoving;
                this.isMoving = false;
                
                // 计算与玩家的距离
                const dx = this.x - player.x;
                const dy = this.y - player.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                let moveX = 0;
                let moveY = 0;

                // 如果玩家太近，就逃跑
                if (distance < this.fleeDistance) {
                    // 结束随机移动状态
                    this.isRandomMoving = false;
                    
                    const angle = Math.atan2(dy, dx);
                    moveX = Math.cos(angle) * this.speed;
                    moveY = Math.sin(angle) * this.speed;
                    this.direction = dx > 0 ? 'right' : 'left';
                    this.isMoving = true;
                }
                // 如果狮子在庆祝或者距离足够远，就考虑向中心移动
                else if ((gameState.isCelebrating || distance > this.fleeDistance * 3) && Math.random() < 0.02) {
                    const centerX = SCREEN_WIDTH / 2 - this.width / 2;
                    const centerY = SCREEN_HEIGHT / 2 - this.height / 2;
                    const centerDx = centerX - this.x;
                    const centerDy = centerY - this.y;
                    const centerDist = Math.sqrt(centerDx * centerDx + centerDy * centerDy);
                    
                    // 只有当距离中心足够远时才移动
                    if (centerDist > 100) {
                        moveX = centerDx / centerDist * this.speed * 0.4;
                        moveY = centerDy / centerDist * this.speed * 0.4;
                        this.direction = centerDx > 0 ? 'right' : 'left';
                        this.isMoving = true;
                        console.log('羚羊正在向中心移动');
                    }
                }
                // 随机移动状态
                else if (this.isRandomMoving) {
                    this.randomMoveCounter--;
                    
                    switch(this.randomMoveDirection) {
                        case 0: // 上
                            moveY = -this.speed * 0.7;
                            break;
                        case 1: // 右
                            moveX = this.speed * 0.7;
                            this.direction = 'right';
                            break;
                        case 2: // 下
                            moveY = this.speed * 0.7;
                            break;
                        case 3: // 左
                            moveX = -this.speed * 0.7;
                            this.direction = 'left';
                            break;
                    }
                    
                    this.isMoving = true;
                    
                    if (this.randomMoveCounter <= 0) {
                        this.isRandomMoving = false;
                    }
                }
                // 静止状态，有概率开始随机移动
                else if (Math.random() < RANDOM_MOVE_CHANCE) {
                    this.isRandomMoving = true;
                    this.randomMoveCounter = RANDOM_MOVE_DURATION;
                    this.randomMoveDirection = Math.floor(Math.random() * 4);
                }
                // 默认的微小随机移动
                else {
                    this.moveTimer++;
                    if (this.moveTimer > this.moveInterval) {
                        this.moveAngle = Math.random() * Math.PI * 2;
                        this.moveTimer = 0;
                        this.moveInterval = Math.random() * 1000 + 500;
                    }
                    moveX = Math.cos(this.moveAngle) * (this.speed * 0.2);
                    moveY = Math.sin(this.moveAngle) * (this.speed * 0.2);
                    this.isMoving = Math.abs(moveX) > 0.05 || Math.abs(moveY) > 0.05;
                }
                
                this.x += moveX;
                this.y += moveY;

                // 边界检查
                const margin = 50;
                if (this.x < -margin) this.x = -margin;
                if (this.x > SCREEN_WIDTH - this.width + margin) this.x = SCREEN_WIDTH - this.width + margin;
                if (this.y < -margin) this.y = -margin;
                if (this.y > SCREEN_HEIGHT - this.height + margin) this.y = SCREEN_HEIGHT - this.height + margin;
                
                // 更新动画
                if (this.isMoving) {
                    this.frameCounter++;
                    if (this.frameCounter >= this.frameDelay) {
                        this.currentFrame = (this.currentFrame + 1) % this.totalFrames;
                        this.frameCounter = 0;
                    }
                } else if (wasMoving) {
                    this.currentFrame = 0;
                }
            }

            render(ctx) {
                ctx.save();
                const sourceX = this.currentFrame * this.frameWidth;
                const sourceY = 0;
                
                if (this.direction === 'right') {
                    ctx.scale(-1, 1);
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        -this.x - this.width, this.y,
                        this.width, this.height
                    );
                } else {
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        this.x, this.y,
                        this.width, this.height
                    );
                }
                ctx.restore();
            }

            getBounds() {
                return {
                    x: this.x,
                    y: this.y,
                    width: this.width,
                    height: this.height
                };
            }
        }

        // 野猪类
        class Pig {
            constructor() {
                this.width = 48;
                this.height = 48;
                // 随机在地图边缘生成
                const spawnEdge = Math.floor(Math.random() * 4);
                switch(spawnEdge) {
                    case 0: // 上边
                        this.x = Math.random() * (SCREEN_WIDTH - this.width);
                        this.y = -this.height;
                        break;
                    case 1: // 右边
                        this.x = SCREEN_WIDTH;
                        this.y = Math.random() * (SCREEN_HEIGHT - this.height);
                        break;
                    case 2: // 下边
                        this.x = Math.random() * (SCREEN_WIDTH - this.width);
                        this.y = SCREEN_HEIGHT;
                        break;
                    case 3: // 左边
                        this.x = -this.width;
                        this.y = Math.random() * (SCREEN_HEIGHT - this.height);
                        break;
                }
                
                this.speed = GOAT_SPEED * 1.2;
                this.direction = 'left';
                this.img = new Image();
                this.fleeDistance = 150;
                this.chargeCooldown = 0;
                
                // 随机移动相关属性
                this.moveTimer = 0;
                this.moveInterval = Math.random() * 1000 + 500;
                this.moveAngle = Math.random() * Math.PI * 2;
                
                // 动画相关属性
                this.frameWidth = 48;
                this.frameHeight = 48;
                this.totalFrames = 4;
                this.currentFrame = 0;
                this.frameCounter = 0;
                this.frameDelay = 10;
                this.isMoving = false;
            }

            update(player) {
                // 重置移动状态
                let wasMoving = this.isMoving;
                this.isMoving = false;
                
                // 计算与玩家的距离
                const dx = this.x - player.x;
                const dy = this.y - player.y;
                const distance = Math.sqrt(dx * dx + dy * dy);
                
                let moveX = 0;
                let moveY = 0;

                // 如果玩家太近，就逃跑或攻击
                if (distance < this.fleeDistance) {
                    if (this.chargeCooldown <= 0 && Math.random() < 0.01) {
                        // 有1%概率发动冲锋攻击
                        moveX = -dx / distance * this.speed * 2;
                        moveY = -dy / distance * this.speed * 2;
                        this.chargeCooldown = 180; // 3秒冷却
                        this.direction = dx > 0 ? 'right' : 'left';
                    } else {
                        // 普通逃跑
                        const angle = Math.atan2(dy, dx);
                        moveX = Math.cos(angle) * this.speed;
                        moveY = Math.sin(angle) * this.speed;
                        this.direction = dx > 0 ? 'right' : 'left';
                    }
                    this.isMoving = true;
                    
                    if (this.chargeCooldown > 0) {
                        this.chargeCooldown--;
                    }
                } else {
                    // 随机移动
                    this.moveTimer++;
                    if (this.moveTimer > this.moveInterval) {
                        this.moveAngle = Math.random() * Math.PI * 2;
                        this.moveTimer = 0;
                        this.moveInterval = Math.random() * 1000 + 500;
                    }
                    moveX = Math.cos(this.moveAngle) * (this.speed * 0.3);
                    moveY = Math.sin(this.moveAngle) * (this.speed * 0.3);
                    this.isMoving = Math.abs(moveX) > 0.1 || Math.abs(moveY) > 0.1;
                }
                
                this.x += moveX;
                this.y += moveY;

                // 边界检查
                const margin = 50;
                if (this.x < -margin) this.x = -margin;
                if (this.x > SCREEN_WIDTH - this.width + margin) this.x = SCREEN_WIDTH - this.width + margin;
                if (this.y < -margin) this.y = -margin;
                if (this.y > SCREEN_HEIGHT - this.height + margin) this.y = SCREEN_HEIGHT - this.height + margin;
                
                // 更新动画
                if (this.isMoving) {
                    this.frameCounter++;
                    if (this.frameCounter >= this.frameDelay) {
                        this.currentFrame = (this.currentFrame + 1) % this.totalFrames;
                        this.frameCounter = 0;
                    }
                } else if (wasMoving) {
                    this.currentFrame = 0;
                }
            }

            render(ctx) {
                ctx.save();
                const sourceX = this.currentFrame * this.frameWidth;
                const sourceY = 0;
                
                if (this.direction === 'right') {
                    ctx.scale(-1, 1);
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        -this.x - this.width, this.y,
                        this.width, this.height
                    );
                } else {
                    ctx.drawImage(
                        this.img,
                        sourceX, sourceY,
                        this.frameWidth, this.frameHeight,
                        this.x, this.y,
                        this.width, this.height
                    );
                }
                ctx.restore();
            }

            getBounds() {
                return {
                    x: this.x,
                    y: this.y,
                    width: this.width,
                    height: this.height
                };
            }
        }

        // 游戏状态
        let gameState = {
            score: 0,
            isGameOver: false,
            isPlaying: false,
            debug: false,
            preloadedImages: {},
            captureAnimations: [],
            isCelebrating: false,
            celebrateFrame: 0,
            lastCaptureTime: 0
        };

        // 游戏变量
        let player;
        let goats = [];
        let pigs = [];
        let lastSpawnTime = 0;
        const keys = {};

        // 检查碰撞
        function checkCollision(rect1, rect2) {
            return rect1.x < rect2.x + rect2.width &&
                   rect1.x + rect1.width > rect2.x &&
                   rect1.y < rect2.y + rect2.height &&
                   rect1.y + rect1.height > rect2.y;
        }

        // 初始化地图数据
        let mapData = [];
        function initMap() {
            mapData = [];
            for (let row = 0; row < MAP_ROWS; row++) {
                const rowData = [];
                for (let col = 0; col < MAP_COLS; col++) {
                    rowData.push(Math.floor(Math.random() * 4));
                }
                mapData.push(rowData);
            }
        }

        // 渲染地图
        function renderMap(ctx, bgTilesheet) {
            for (let row = 0; row < mapData.length; row++) {
                for (let col = 0; col < mapData[row].length; col++) {
                    const tileType = mapData[row][col];
                    const tileX = (tileType % 2) * TILE_SIZE;
                    const tileY = Math.floor(tileType / 2) * TILE_SIZE;
                    
                    ctx.drawImage(
                        bgTilesheet,
                        tileX, tileY,
                        TILE_SIZE, TILE_SIZE,
                        col * TILE_SIZE, row * TILE_SIZE,
                        TILE_SIZE, TILE_SIZE
                    );
                }
            }
        }

        // 创建初始动物
        function createInitialAnimals() {
            // 创建羚羊
            for (let i = 0; i < INITIAL_GOATS; i++) {
                const goat = new Goat();
                if (gameState.preloadedImages.goat) {
                    goat.img = gameState.preloadedImages.goat;
                }
                goats.push(goat);
            }
            
            // 创建野猪
            for (let i = 0; i < INITIAL_PIGS; i++) {
                const pig = new Pig();
                if (gameState.preloadedImages.pig) {
                    pig.img = gameState.preloadedImages.pig;
                }
                pigs.push(pig);
            }
        }

        // 尝试生成新动物
        function trySpawnNewAnimals(currentTime) {
            // 生成新羚羊
            if (currentTime - lastSpawnTime > GOAT_SPAWN_INTERVAL && goats.length < MAX_GOATS) {
                const goat = new Goat();
                if (gameState.preloadedImages.goat) {
                    goat.img = gameState.preloadedImages.goat;
                }
                goats.push(goat);
                console.log('新羚羊出现！当前数量:', goats.length);
            }
            
            // 生成新野猪
            if (currentTime - lastSpawnTime > GOAT_SPAWN_INTERVAL && pigs.length < MAX_PIGS) {
                const pig = new Pig();
                if (gameState.preloadedImages.pig) {
                    pig.img = gameState.preloadedImages.pig;
                }
                pigs.push(pig);
                console.log('新野猪出现！当前数量:', pigs.length);
            }
            
            if (goats.length < MAX_GOATS || pigs.length < MAX_PIGS) {
                lastSpawnTime = currentTime;
            }
        }

        // 游戏主循环
        function gameLoop(timestamp) {
            if (!gameState.isPlaying) return;
            
            // 尝试生成新动物
            trySpawnNewAnimals(Date.now());

            // 清空画布
            ctx.fillStyle = '#000000';
            ctx.fillRect(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
            
            // 渲染地图
            renderMap(ctx, gameState.preloadedImages.bgTilesheet);
            
            // 显示调试信息
            if (gameState.debug) {
                ctx.fillStyle = 'rgba(0, 0, 0, 0.5)';
                ctx.fillRect(10, SCREEN_HEIGHT - 90, 200, 80);
                ctx.fillStyle = 'white';
                ctx.font = '12px Arial';
                ctx.fillText(`狮子帧: ${player.currentFrame}/${player.totalFrames}`, 20, SCREEN_HEIGHT - 70);
                ctx.fillText(`狮子移动: ${player.isMoving ? '是' : '否'}`, 20, SCREEN_HEIGHT - 55);
                ctx.fillText(`羚羊数量: ${goats.length}/${MAX_GOATS}`, 20, SCREEN_HEIGHT - 40);
                ctx.fillText(`野猪数量: ${pigs.length}/${MAX_PIGS}`, 20, SCREEN_HEIGHT - 25);
                ctx.fillText(`庆祝状态: ${gameState.isCelebrating ? '是' : '否'}`, 20, SCREEN_HEIGHT - 10);
            }

            // 更新玩家
            player.update(keys);

            // 更新羚羊
            for (let i = goats.length - 1; i >= 0; i--) {
                goats[i].update(player);
                
                // 检查捕获
                if (checkCollision(player.getBounds(), goats[i].getBounds())) {
                    gameState.score++;
                    goats.splice(i, 1);
                    
                    // 添加捕获动画
                    gameState.captureAnimations.push(
                        new CaptureAnimation(player.x + player.width/2, player.y, 1)
                    );
                    
                    // 触发庆祝动画
                    player.celebrate();
                    
                    // 显示捕获提示
                    ctx.fillStyle = 'white';
                    ctx.font = 'bold 36px Arial';
                    ctx.fillText('捕获羚羊！', SCREEN_WIDTH/2 - 80, SCREEN_HEIGHT/2);
                }
            }
            
            // 更新野猪
            for (let i = pigs.length - 1; i >= 0; i--) {
                pigs[i].update(player);
                
                // 检查捕获
                if (checkCollision(player.getBounds(), pigs[i].getBounds())) {
                    gameState.score += 2; // 野猪分值更高
                    pigs.splice(i, 1);
                    
                    // 添加捕获动画
                    gameState.captureAnimations.push(
                        new CaptureAnimation(player.x + player.width/2, player.y, 2)
                    );
                    
                    // 触发庆祝动画
                    player.celebrate();
                    
                    // 显示捕获提示
                    ctx.fillStyle = 'white';
                    ctx.font = 'bold 36px Arial';
                    ctx.fillText('捕获野猪！', SCREEN_WIDTH/2 - 80, SCREEN_HEIGHT/2);
                }
            }
            
            // 更新捕获动画
            gameState.captureAnimations = gameState.captureAnimations.filter(anim => {
                anim.update();
                return !anim.isFinished();
            });

            // 渲染游戏对象
            goats.forEach(goat => goat.render(ctx));
            pigs.forEach(pig => pig.render(ctx));
            player.render(ctx);
            
            // 渲染捕获动画
            gameState.captureAnimations.forEach(anim => anim.render(ctx));

            // 显示游戏信息
            ctx.fillStyle = 'white';
            ctx.font = 'bold 24px Arial';
            ctx.fillText(`分数: ${gameState.score}`, 10, 30);
            ctx.fillText(`羚羊: ${goats.length}/${MAX_GOATS}`, 10, 60);
            ctx.fillText(`野猪: ${pigs.length}/${MAX_PIGS}`, 10, 90);

            // 继续游戏循环
            requestAnimationFrame(gameLoop);
        }

        // 预加载所有图像
        function preloadImages(callback) {
            const imagesToLoad = [
                { name: 'bgTilesheet', src: 'pics/background.png' },
                { name: 'lion', src: 'pics/lion.png' },
                { name: 'goat', src: 'pics/goat.png' },
                { name: 'pig', src: 'pics/pig.png' }
            ];
            
            let loadedImages = 0;
            const images = {};
            
            imagesToLoad.forEach(img => {
                const image = new Image();
                image.onload = () => {
                    images[img.name] = image;
                    loadedImages++;
                    if (loadedImages === imagesToLoad.length) {
                        callback(images);
                    }
                };
                image.onerror = () => {
                    console.error(`Failed to load image: ${img.src}`);
                    loadedImages++;
                    if (loadedImages === imagesToLoad.length) {
                        callback(images);
                    }
                };
                image.src = img.src;
            });
        }

        // 初始化游戏
        function initGame(images) {
            // 保存预加载的图像
            gameState.preloadedImages = images;
            
            // 初始化地图
            initMap();
            
            // 创建玩家
            player = new Player();
            player.img = images.lion;
            
            // 创建初始动物
            createInitialAnimals();
            
            // 初始化生成时间
            lastSpawnTime = Date.now();
            
            // 开始游戏
            gameState.isPlaying = true;
            document.getElementById('startScreen').style.display = 'none';
            gameLoop();
        }

        // 键盘事件监听
        window.addEventListener('keydown', (e) => {
            keys[e.key] = true;
            
            // 按D键切换调试模式
            if (e.key === 'd' || e.key === 'D') {
                gameState.debug = !gameState.debug;
                console.log(`调试模式: ${gameState.debug ? '开启' : '关闭'}`);
            }
        });
        window.addEventListener('keyup', (e) => keys[e.key] = false);

        // 开始按钮事件监听
        document.getElementById('startButton').addEventListener('click', () => {
            document.getElementById('startButton').disabled = true;
            document.getElementById('startButton').textContent = '加载中...';
            
            // 预加载所有图像
            preloadImages(initGame);
        });
    </script>
</body>
</html>